package impl

import (
	"context"

	"gitee.com/fzh-show/mcenter/apps/token"
	"gitee.com/fzh-show/mcenter/apps/user"
	"github.com/infraboard/mcube/v2/exception"
	"go.mongodb.org/mongo-driver/bson"
)

func (i *impl) IssueToken(ctx context.Context, in *token.IssueTokenRequest) (*token.Token, error) {
	u, err := i.user.Describe(ctx, user.NewDescribeUserRequest(in.Username))
	if err != nil {
		return nil, err
	}
	err = u.CheckPassword(in.Password)
	if err != nil {
		return nil, err
	}
	tk := token.NewToken()
	tk.Username = in.Username
	// 保存token
	_, err = i.col.InsertOne(ctx, tk)
	if err != nil {
		return nil, err
	}
	return tk, nil
}

func (i *impl) ValidateToken(ctx context.Context, in *token.ValidateTokenRequest) (*token.Token, error) {
	// 先找到token
	tk, err := i.DescribeToken(ctx, token.NewDescribeTokenRequest(in.AcceessToken))
	if err != nil {
		return nil, err
	}
	// 判断token有效性
	if tk.IsAccessTokenExpired() {
		return nil, exception.NewUnauthorized("令牌已过期,请重新登录或者刷新")
	}

	// 判断

	return tk, nil
}

// 查询令牌详情
func (i *impl) DescribeToken(ctx context.Context, in *token.DescribeTokenRequest) (*token.Token, error) {
	res := i.col.FindOne(ctx, bson.M{"access_token": in.AcceessToken})
	ins := token.NewToken()
	err := res.Decode(ins)
	if err != nil {
		return nil, err
	}
	return ins, err
}

func (i *impl) RevolkToken(ctx context.Context, in *token.RevolkTokenRequest) (*token.Token, error) {
	return nil, nil
}
